package com.igeek.boot.controller;

import com.github.pagehelper.PageInfo;
import com.igeek.boot.entity.User;
import com.igeek.boot.service.IUserService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/8/21  9:49
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    //post 添加用户  （name age gender pwd birthday）
    @PostMapping("/add")
    public boolean add(@RequestBody User user){
        return userService.insertUser(user);
    }

    //put 根据id 更新用户头像 （pic）  并且实现文件上传
    @PutMapping("/upload")
    public boolean upload(User user, MultipartFile photo) throws IOException {
        if(!photo.isEmpty()){
            String oldName = photo.getOriginalFilename();
            String newName = UUID.randomUUID()+oldName.substring(oldName.lastIndexOf("."));
            photo.transferTo(new File("D:\\133java\\1.SpringBoot\\pic\\"+newName));

            //上传后 设置数据库中pic字段的值
            user.setPic("/pic/"+newName);
        }else {
            user.setPic("");
        }
        return userService.updatePic(user);
    }

    //delete 根据id 删除用户
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable("id") int id){
        return userService.deleteOne(id);
    }


    //get 根据name模糊查询用户信息
    @GetMapping("/list/{name}")
    public List<User> list(@PathVariable("name") String name){
        return userService.queryByName(name);
    }

    //分页查询
    @GetMapping("/page/{name}/{current}")
    public PageInfo<User> page(@PathVariable("current") int current,@PathVariable("name") String name){
        PageInfo<User> pageInfo = userService.selectListByPage(current, name);
        return pageInfo;
    }

}
